package com.sdkx.app.activitys;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.location.Location;
import android.location.LocationListener;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.sdkx.app.R;
import com.sdkx.app.TimerService;
import com.sdkx.app.ViewModel.TrackPointManager;
import com.sdkx.app.dialog.SearchDialog;
//import com.sdkx.app.dialog.toolsDialog;

import com.sdkx.app.fragment.MainMenuFragmentView;
import com.sdkx.app.fragment.RoutesFragmentView1;
import com.sdkx.app.gps.GpsManager;
import com.sdkx.app.util.ToastUtil;
import com.sdkx.app.util.Util;
import com.sdkx.app.view.MyMapView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.creable.gridgis.controls.App;
import cn.creable.gridgis.controls.MapControl;
import cn.creable.gridgis.controls.MeasureTool;
import cn.creable.gridgis.display.IDisplayTransformation;
import cn.creable.gridgis.geometry.IEnvelope;
import cn.creable.gridgis.geometry.Point;
import cn.creable.gridgis.shapefile.FixedShapefileLayer;
import cn.creable.ucmap.OpenSourceMapLayer;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,LocationListener{
    public TextView tv_main_title;
    // 新换的布局
    private LinearLayout ll_mainmenu_include_context;
    public MyMapView mapView;
    private Button button_end_distance ;
    //截屏相关参数
    private static final int REQUEST_MEDIA_PROJECTION = 1;
    private int mScreenDensity;
    private int mWindowWidth;
    private int mWindowHeight;
    private int mResultCode;
    private Intent mResultData;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjectionManager mMediaProjectionManager;
    private ImageReader mImageReader;
    private final String imagePath = Environment.getExternalStorageDirectory().toString() + "/pictures/screenshots";
    private boolean planeIncenter = true;

    Handler handler = new Handler();
    /**
     * 航迹记录
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 这句代码修复点击屏幕顶部不灵敏。
        getWindow().setFlags(1024, 1024);
        //网络上找到的防止返回丢失内容的例子
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        //
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.menu);
        }
        initView();
        GpsManager.getInstance().addLocationListener(this);
        //InitEvent();
        App.getInstance().scale = 1.5f;// 修改显示注释字体大小
//        new Thread(){
//            @Override
//            public void run() {
//                TrackPointManager.insertdata();
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        ToastUtil.show(MainActivity.this,"数据填充完毕",Gravity.BOTTOM);
//                    }
//                },500);
//            }
//        }.start();
       // ToastUtil.show(MainActivity.this,"数据填充完毕",Gravity.BOTTOM);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mapView.centerTo(116.156985,40.065789,true);
            }
        },1000);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home://导航菜单按键
                showNavigationMenu();
                break;
            case R.id.menu_nearest://最近的
                Intent intent = new Intent(MainActivity.this, NearestActivity.class);
                //TODO: 设置当前位置信息
//                intent.putExtra("longitude",180);
//                intent.putExtra("latitude",180);
                startActivity(intent);
                break;
            case R.id.menu_search://搜索
                SearchDialog searchDialog = new SearchDialog(this, "搜索");
                searchDialog.show();
                break;
            case R.id.menu_timer://计时器
                startService(new Intent(MainActivity.this, TimerService.class));
                break;
            case R.id.menu_crop://截屏
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        saveCapture();
                    }
                },50);
                break;
            case R.id.menu_distance://测距:
                if(button_end_distance.getVisibility()!=View.VISIBLE) {
                    MeasureTool measureTool = new MeasureTool(mapView.getMapControl(),0);//第二个参数为 0 表示测距离，1 则表示测面积
                    measureTool.selector.setOffset(0,60);
                    mapView.getMapControl().setCurrentTool(measureTool);
                    button_end_distance.setVisibility(View.VISIBLE);
                    break;
                }
            case R.id.menu_setting://设置
                Intent intent2 = new Intent(MainActivity.this, SettingActivity.class);
                intent2.putExtra("type","main");
                startActivity(intent2);
                break;
            default:
                break;
        }
        return true;
    }

    /*********************************截屏相关代码开始*********************************************************/
    @Override
    protected void onStart() {
        super.onStart();
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;
        mWindowWidth = metrics.widthPixels;
        mWindowHeight = metrics.heightPixels;
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startScrrenCapture();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopScreenCapture();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tearDownMediaProjection();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != RESULT_OK) {
                return;
            }
            mResultCode = resultCode;
            mResultData = data;
            mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight, PixelFormat.RGBA_8888, 1);
            setUpMediaProjection();
            setUpVirtualDisplay();
        }
    }

    private void saveCapture() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String strDate = dateFormat.format(new Date());
        String imageName = strDate + ".png";
        Image image = mImageReader.acquireLatestImage();
        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        image.close();
        if (bitmap != null) {
            try {
                File fileFolder = new File(imagePath);
                if (!fileFolder.exists()) {
                    fileFolder.mkdirs();
                }
                File file = new File(imagePath, imageName);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
//                Toast.makeText(MainActivity.this, "截屏完成", Toast.LENGTH_SHORT).show();
                ToastUtil.show(this,"截屏完成");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void startScrrenCapture() {
        if (mMediaProjection != null) {
            setUpVirtualDisplay();
        } else if (mResultCode != 0 && mResultData != null) {
            setUpMediaProjection();
            setUpVirtualDisplay();
        } else {
            // This initiates a prompt dialog for the user to confirm screen projection.
            startActivityForResult(
                    mMediaProjectionManager.createScreenCaptureIntent(),
                    REQUEST_MEDIA_PROJECTION);
        }
    }

    private void setUpMediaProjection() {
        mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData);
    }

    private void tearDownMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

    private void setUpVirtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture",
                mWindowWidth, mWindowHeight, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
    }

    private void stopScreenCapture() {
        if (mVirtualDisplay == null) {
            return;
        }
        mVirtualDisplay.release();
        mVirtualDisplay = null;
    }

    @Override
    public void onClick(View view) {

    }

    private void showNavigationMenu() {
        if (ll_mainmenu_include_context.isShown()) {
            ll_mainmenu_include_context.setVisibility(View.GONE);
            getSupportFragmentManager().popBackStack(null, 1);
        } else {
            //ShowMainMenu(0);
            int count = getSupportFragmentManager().getBackStackEntryCount();
            Log.d("MainActivity", "count = " + count);
            List<Fragment> list = getSupportFragmentManager().getFragments();
            boolean flag = false;
            for (Fragment fragment : list) {
                if (fragment != null && fragment.getClass().equals(MainMenuFragmentView.class)) {
                    popToFragment(MainMenuFragmentView.class);
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                startFragment(MainMenuFragmentView.class);
            }
            // transaction.replace(R.id.layer1, mMainMenuFragmentView);
            ll_mainmenu_include_context.setVisibility(View.VISIBLE);
        }
    }

    //系统返回按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //主菜单
            if (ll_mainmenu_include_context.getVisibility() == View.VISIBLE) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                    return true;
                }
                // 隐藏主菜单
                ll_mainmenu_include_context.setVisibility(View.GONE);
                return true;
            }

            AlertDialog.Builder dialogx = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_TRADITIONAL);
            dialogx.setIcon(android.R.drawable.ic_dialog_alert);// 设置标题的图片
            dialogx.setTitle("提醒");// 设置标题
            dialogx.setCancelable(false);
            dialogx.setMessage("是否要退出");// 设置对话框的内容
            dialogx.setNegativeButton("确定", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // AppManager.getAppManager().AppExit(MainActivity.this);
                    MainActivity.this.finish();
                }
            });
            dialogx.setPositiveButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialogx.show();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {

            if (ll_mainmenu_include_context.getVisibility() == View.GONE) {
                // 展示主菜单
                //ShowMainMenu(1);
                startFragment(RoutesFragmentView1.class);
                return true;
            } else {
                // 隐藏主菜单
                ll_mainmenu_include_context.setVisibility(View.GONE);
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showToolPopupWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.tool_pop, null);
        Button button_timer = (Button) contentView.findViewById(R.id.button_timer);
        Button button_crop = (Button) contentView.findViewById(R.id.button_crop);
        Button button_range = (Button) contentView.findViewById(R.id.button_range);
        button_timer.setOnClickListener(this);
        button_crop.setOnClickListener(this);
        button_range.setOnClickListener(this);
        PopupWindow toolPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        ColorDrawable cd = new ColorDrawable(0x000000);
        toolPopupWindow.setBackgroundDrawable(cd);
        toolPopupWindow.setOutsideTouchable(true);
        toolPopupWindow.setFocusable(true);
        toolPopupWindow.showAsDropDown(view);
    }

    private void initView() {
        ll_mainmenu_include_context = (LinearLayout) findViewById(R.id.ll_mainmenu_include_context);
        mapView = (MyMapView) findViewById(R.id.mapview);
        button_end_distance = (Button)findViewById(R.id.button_end_distance);
        button_end_distance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapView.getMapControl().setPanTool();
                button_end_distance.setVisibility(View.GONE);
            }
        });
        findViewById(R.id.gps_focus).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                planeIncenter = false;
                Location location = GpsManager.getInstance().getLocation();
                if(location != null) {
                    mapView.centerTo(location.getLongitude(), location.getLatitude(), true);

                }else{
                    mapView.centerTo(116.156985,40.065789,true);
                }
                mapView.getMapControl().getDisplay().getDisplayTransformation().setZoom(0.0011349015f);
            }
        });
        mapView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    ll_mainmenu_include_context.setVisibility(View.GONE);
                    getSupportFragmentManager().popBackStack(null, 1);
                }
                return false;
            }
        });
    }
//Military Fixed Data
    public MapControl getMapControl(){
        return mapView.getMapControl();
    }

    @Override
    public void onLocationChanged(Location location) {
        if(planeIncenter){
            mapView.centerTo(location.getLongitude(),location.getLatitude(),true);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}